package com.chinasofti.thread06;
public class SellTicket implements Runnable {
    private static  int ticketsCount = 100;
    @Override
    public void run() {
        while (true){
            //窗口1
            if("窗口1".equals(Thread.currentThread().getName())){
                //同步方法
                boolean result = synchronizedMethod();
                if (result){
                    break;
                }
            }
            if("窗口2".equals(Thread.currentThread().getName())){
                //同步代码块
                synchronized(SellTicket.class){
                    if(ticketsCount == 0){
                        break;
                    }else {
                        try {
                            Thread.sleep(100);
                            //t1休息了100毫秒
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        //窗口1收票1张
                        ticketsCount--;
                        System.out.println(Thread.currentThread().getName() + "在卖票，还剩下" + ticketsCount + "张票");
                    }
                }

            }


        }
    }
    //同步方法
    private static synchronized boolean synchronizedMethod(){
        if (ticketsCount == 0) {
            return true;
        } else {
            try {
                Thread.sleep(100);
                //t1休息了100毫秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //窗口1收票1张
            ticketsCount--;
            System.out.println(Thread.currentThread().getName() + "在卖票，还剩下" + ticketsCount + "张票");
            return false;
        }
    }

}